import { deleteCategory, getCategory } from '@/services/ant-design-pro/api';
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import {
  FooterToolbar,
  PageContainer,
  ProTable,
} from '@ant-design/pro-components';
import { FormattedMessage, useIntl, useRequest } from '@umijs/max';
import { Button, message } from 'antd';
import React, { useCallback, useRef, useState } from 'react';
import CreateForm from './components/CreateForm';
import EditForm from './components/EditForm';

const TableList: React.FC = () => {
  const actionRef = useRef<ActionType>();

  const [selectedRowsState, setSelectedRows] = useState<API.CategoryListItem[]>([]);

  /**
   * @en-US International configuration
   * @zh-CN 国际化配置
   * */
  const intl = useIntl();
  const [messageApi, contextHolder] = message.useMessage();


  /*
  const { run: delRun, loading } = useRequest(...): 这里使用了解构赋值。
run: 这是 useRequest 返回的一个函数，用于触发请求。
delRun: 这是将 run 重命名为 delRun，以便更清楚地表示这是一个用于删除操作的函数。
loading: 这是一个布尔值，指示请求是否正在进行中。你可以使用这个值来显示加载状态（例如，禁用按钮或显示加载指示器）。
  */
  const { run: delRun, loading } = useRequest(deleteCategory, {
    manual: true,
    onSuccess: () => {
      setSelectedRows([]);
      actionRef.current?.reloadAndRest?.();
      messageApi.success('成功删除');
    },
    onError: () => {
      messageApi.error('删除失败');
    },
  });

  const columns: ProColumns<API.CategoryListItem>[] = [
    {
      title: <FormattedMessage id="pages.category.category" defaultMessage="类别号" />,
      dataIndex: 'category',
      sorter: true,
      tooltip: '此为类别的代号，如1代表资产类别',
    },
    {
      title: <FormattedMessage id="pages.category.categorydesc" defaultMessage="类别号描述" />,
      dataIndex: 'categorydesc',
      sorter: true,
      
    },
    {
      title: <FormattedMessage id="pages.category.type" defaultMessage="类型号" />,
      dataIndex: 'type',
      sorter: true,
      tooltip: '此为某个类别下的类型号，如1代表资产类别下的设备',
    },
   
    {
      title: <FormattedMessage id="pages.category.description" defaultMessage="描述" />,
      dataIndex: 'description',
    },

    //操作
    {
      title: <FormattedMessage id="pages.searchTable.titleOption" defaultMessage="Operating" />,
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => [
        <EditForm
          trigger={
            <a>
              <FormattedMessage id="pages.edit" defaultMessage="edit" />
            </a>
          }
          key="edit"
          //这个不是提交的函数，而是修改后重新渲染表单的函数
          onOk={actionRef.current?.reload}
          values={record}
        />,
      ],
    },
  ];

  /**
   *  Delete node
   * @zh-CN 删除节点
   *
   * @param selectedRows
   */
  const handleRemove = useCallback(
    async (selectedRows: API.CategoryListItem[]) => {
      if (!selectedRows?.length) {
        messageApi.warning('请选择删除项');

        return;
      }
      await delRun(selectedRows.map((row) => row.key));
    },
    [delRun],
  );

  return (
    <PageContainer>
      {contextHolder}
      <ProTable<API.CategoryListItem, API.PageParams>
        headerTitle={intl.formatMessage({
          id: 'pages.category.title',
          defaultMessage: '类别表',
        })}
        actionRef={actionRef}
        rowKey="key"
        search={{
          labelWidth: 120,
        }}
        toolBarRender={() => [<CreateForm key="create" reload={actionRef.current?.reload} />]}
        request={getCategory}
        columns={columns}
        rowSelection={{
          onChange: (_, selectedRows) => {
            setSelectedRows(selectedRows);
          },
        }}
      />

      {selectedRowsState?.length > 0 && (
        <FooterToolbar
          extra={
            <div>
              <FormattedMessage id="pages.searchTable.chosen" defaultMessage="Chosen" />{' '}
              <a style={{ fontWeight: 600 }}>{selectedRowsState.length}</a>{' '}
              <FormattedMessage id="pages.searchTable.item" defaultMessage="项" />
              &nbsp;&nbsp;
           
            </div>
          }
        >
          <Button
            type="primary"
            loading={loading}
            onClick={() => {
              handleRemove(selectedRowsState);
            }}
          >
            <FormattedMessage
              id="pages.searchTable.batchDeletion"
              defaultMessage="Batch deletion"
            />
          </Button>
      
        </FooterToolbar>
      )}

      {/* <Drawer
        width={600}
        open={showDetail}
        onClose={() => {
          setCurrentRow(undefined);
          setShowDetail(false);
        }}
        closable={false}
      >
        {currentRow?.assetsname && (
          <ProDescriptions<API.AssetsListItem>
            column={2}
            title={currentRow?.assetsname}
            request={async () => ({
              data: currentRow || {},
            })}
            params={{
              id: currentRow?.assetsname,
            }}
            columns={columns as ProDescriptionsItemProps<API.AssetsListItem>[]}
          />
        )}
      </Drawer> */}
    </PageContainer>
  );
};

export default TableList;
